package com.blue.gateway.config.filters.global;

import com.blue.gateway.constant.AuthProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.CollectionUtils;
import org.springframework.util.PathMatcher;
import org.springframework.web.server.ServerWebExchange;

import java.util.Base64;
import java.util.List;

/**
 * @author liulei
 * @version 1.0
 */
@Slf4j
public abstract class AbstractGatewayFilter {

    protected static final PathMatcher pathMatcher = new AntPathMatcher();
    protected static final Base64.Encoder encoder = Base64.getEncoder();

    @Autowired
    private AuthProperties authProperties;

    /**
     * 判断url是否需要忽略
     */
    public boolean isIgnoreUrl(ServerWebExchange exchange) {
        // 人为设置的url忽略
        List<String> excludePatterns = authProperties.getExcludePatterns();
        String path = exchange.getRequest().getURI().getPath();
        if (!CollectionUtils.isEmpty(excludePatterns)) {
            boolean match = excludePatterns.stream().anyMatch(s -> pathMatcher.match(s, path));
            if (match) {
                return true;
            }
        }
        if (isLoginUrl(exchange)) {
            return true;
        }
        return false;
    }

    /**
     * 是否为登录url
     */
    public boolean isLoginUrl(ServerWebExchange exchange) {
        boolean flag = false;
        List<String> loginPatterns = authProperties.getLoginPatterns();
        String path = exchange.getRequest().getURI().getPath();
        if (!CollectionUtils.isEmpty(loginPatterns)) {
            boolean match = loginPatterns.parallelStream().anyMatch(s -> pathMatcher.match(s, path));
            if (match) {
                flag = true;
            }
        }
        return flag;
    }
}
